package com.cos.shop.web.servlet;

import com.cos.shop.common.Const;
import com.cos.shop.common.ResponseResult;
import com.cos.shop.entity.Address;
import com.cos.shop.entity.User;
import com.cos.shop.service.AddressServices;
import com.cos.shop.service.impl.AddressServicesImpl;
import com.cos.shop.util.StringUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * Copyright (C),2021-2022,亚瑟王
 * FileName: AddressController
 * Author: saber
 * Date:2022/9/19 21:16
 */
@WebServlet("/address")
public class AddressController extends BaseServlet {
    private AddressServices as = new AddressServicesImpl();

    public String addAddress(HttpServletRequest request, HttpServletResponse response){
        String aname = request.getParameter("name");
        String adetail = request.getParameter("detail");
        String aphone = request.getParameter("phone");

        User user = (User) request.getSession().getAttribute(Const.SystemConst.IS_LOGIN);

        Address address = new Address(user.getUid(), aname, aphone, adetail,Const.UserCode.NOT_DEFAULT_ADDRESS);

        ResponseResult rr = as.addAddressByUser(address);
        return Const.REDIRECT +"/address?method=getAddress";
    }

    public String getAddress(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute(Const.SystemConst.IS_LOGIN);
        ResponseResult rr = as.getAddressByUser(user.getUid());
        request.setAttribute("rr", rr);
        return Const.FORWARD + "/self_info.jsp";
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) {

        int aid = StringUtils.stringToInt(request.getParameter("aid"));

        ResponseResult rr = as.deleteAddress(aid);

        return Const.REDIRECT + "/address?method=getAddress";
    }

    public String updateAddress(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        Map<String,String[]> map = request.getParameterMap();

        Address address = new Address();

        BeanUtils.populate(address,map);

        ResponseResult rr = as.updateAddress(address);

        return Const.REDIRECT + "/address?method=getAddress";
    }

    public String changeDefault(HttpServletRequest request, HttpServletResponse response) {
        int aid = StringUtils.stringToInt(request.getParameter("aid"));
        User user = (User) request.getSession().getAttribute(Const.SystemConst.IS_LOGIN);

        ResponseResult rr = as.changeDefault(aid,user.getUid());

        return Const.REDIRECT + "/address?method=getAddress";
    }
} 
